package com.hr.email;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hr.utils.BaseServlet;
import com.hr.utils.Mail;
import com.hr.utils.MailUtils;

public class EmailServlet extends BaseServlet {
	
	public String sendEmailPre(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("email_template.properties"));
		String host = props.getProperty("host");
		String uname = props.getProperty("uname");
		String from = props.getProperty("from");
		
		request.setAttribute("host", host);
		request.setAttribute("uname", uname);
		request.setAttribute("from", from);
		return "f:/email/email_send.jsp";
	}
	
	public String sendEmail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String to = request.getParameter("to");
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("email_template.properties"));
		String host = props.getProperty("host");
		String uname = props.getProperty("uname");
		String pwd = props.getProperty("pwd");
		String from = props.getProperty("from");
		String subject = props.getProperty("subject")+request.getParameter("subject");
		String content = request.getParameter("content");
		Session session = MailUtils.createSession(host, uname, pwd);
		Mail mail = new Mail(from,to,subject,content);
		try {
			MailUtils.send(session, mail);
		} catch (MessagingException e) {
			// TODO: handle exception
		}
		//保存成功信息
		//转发到msg.jsp
		request.setAttribute("msg", "恭喜您，邮件发送成功");
		request.setAttribute("host", host);
		request.setAttribute("uname", uname);
		request.setAttribute("from", from);
		request.setAttribute("to", to);
		return "f:/email/email_send.jsp";
	}
}
